package cn.wangliang181230.boot.web.environmentpostprocessor;

import org.springframework.boot.DefaultPropertiesPropertySource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;

import java.util.HashMap;
import java.util.Map;

public class ThdDefaultPropertiesEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {

	@Override
	public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
		System.out.println(this.getClass().getSimpleName() + " : " + environment.getClass().getSimpleName());


		// 获取或创建默认配置源
		MapPropertySource defaultPropertiesPropertySource;
		boolean isPresent = false;
		PropertySource<?> propertySource = environment.getPropertySources().get(DefaultPropertiesPropertySource.NAME);
		if (propertySource instanceof MapPropertySource) {
			defaultPropertiesPropertySource = (MapPropertySource) propertySource;
			isPresent = true;
		} else {
			defaultPropertiesPropertySource = new MapPropertySource(DefaultPropertiesPropertySource.NAME, new HashMap<>());
		}


		// 公司统一采用的默认配置
		Map<String, Object> source = defaultPropertiesPropertySource.getSource();
		source.put("mybatis-plus.global-config.db-config.id-type", "assign_id"); // mybatis-plus的主键策略：雪花算法
		source.put("mybatis-plus.global-config.banner", "true"); // mybatis-plus的banner：显示


		// 将默认配置源放到最后
		if (!isPresent) {
			environment.getPropertySources().addLast(defaultPropertiesPropertySource);
		}
	}


	@Override
	public int getOrder() {
		return Ordered.LOWEST_PRECEDENCE;
	}

}
